const express = require('express');
const router = express.Router();
const rds = require('./rds');
const logger = require('./logger');

// 权限配置对象
const { permissions}  =  require('./admin-auth');

// 统一的管理员权限检查中间件
function adminAuth(req, res, next) {
    const roles = req.session.user?.roles || '';
    // 获取完整的路径，去除开头的/apps/admin和查询参数
    const fullPath = req.originalUrl.split('?')[0].replace('/apps/admin', '');
    const path = fullPath.endsWith('/') ? fullPath.slice(0, -1) : fullPath;

    // 检查用户角色是否有权限访问当前路径
    const hasPermission = roles.split(' ').some(role => {
        const allowedPaths = permissions[role];
        if (!allowedPaths) return false;

        // 使用正则表达式匹配路径
        return allowedPaths.some(allowedPath => {
            const regex = new RegExp(`^${allowedPath.replace(/:\w+/g, '[^/]+')}$`);
            return regex.test(path);
        });
    });

    if (hasPermission) {
        next();
    } else {
        res.status(403).render('warn', {
            title: '访问受限',
            message: '您没有权限访问此页面',
            description: '请联系管理员获取权限',
            icon: 'weui-icon-warn weui-icon_msg'
        });
    }
}

// 管理首页
router.get('/', adminAuth, (req, res) => {
    res.render('admin/index', {
        title: `管理控制台 ${req.session.crmROLE}`,
        menus: [
            { name: '活动管理', url: '/apps/admin/activities', icon: 'fas fa-gift' },
            { name: '商户管理', url: '/apps/admin/merchants', icon: 'fas fa-store' },
            { name: '退款查询', url: '/apps/admin/refunds', icon: 'fas fa-undo' },
            { name: '问卷管理', url: '/apps/admin/surveys', icon: 'fas fa-clipboard-list' },
            { name: '方案管理', url: '/apps/admin/products', icon: 'fas fa-capsules' }
        ]
    });
});

// 引入各个子模块的路由
const activityRoutes = require('./routes/activity');
const merchantRoutes = require('./routes/merchant'); 
const refundRoutes = require('./routes/refund');
const surveyRoutes = require('./routes/survey');
const productRoutes = require('./routes/product');

// 注册子模块路由
router.use('/activities', adminAuth, activityRoutes);
router.use('/merchants', adminAuth, merchantRoutes);
router.use('/refunds', adminAuth, refundRoutes);
router.use('/surveys', adminAuth, surveyRoutes);
router.use('/products', adminAuth, productRoutes);

module.exports = router; 
